package com.panda.common.memcached;

import com.danga.MemCached.MemCachedClient;
import com.danga.MemCached.SockIOPool;

/**
 * 使用单例模式管理我们的客户端缓存设置
 * 
 * @date 2008-09-11
 * @author lhw
 * 
 * */
public class MemcachedFactory {

	private MemcachedFactory() {
	}

	private static MemcachedFactory instance = new MemcachedFactory();

	private static MemCachedClient mcc = null;

	/**
	 * @describe:根据服务器地址,服务器权重,获得HashTable
	 * @param servers
	 *            服务器数组,格式为:{"192.168.36.139","192.168.36.140"}
	 * @param weights
	 *            权重数组 格式为:{3,4,5}
	 * @return MemCachedClient
	 * @throws Exception
	 */
	static {
		mcc = new MemCachedClient();
		MemcachedParam conf = null;
		try {
			conf = new MemcachedParam();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// grab an instance of our connection pool
		SockIOPool pool = SockIOPool.getInstance();

		// set the servers and the weights
		pool.setServers(conf.getServers());
		pool.setWeights(conf.getWeights());
		// System.out.println(conf.getServers()[0]+"++++++++++++++++++++++++");

		// set some basic pool settings
		// 5 initial, 5 min, and 250 max conns
		// and set the max idle time for a conn
		// to 6 hours
		pool.setInitConn(conf.getInitConn());
		pool.setMinConn(conf.getMinConn());
		pool.setMaxConn(conf.getMaxConn());
		pool.setMaxIdle(conf.getMaxIdle());

		// set the sleep for the maint thread
		// it will wake up every x seconds and
		// maintain the pool size
		pool.setMaintSleep(conf.getMaintSleep());

		// set some TCP settings
		// disable nagle
		// set the read timeout to 3 secs
		// and don't set a connect timeout
		pool.setNagle(conf.getNagle());
		// 连接建立后对超时的控制
		pool.setSocketTO(conf.getSocketTo());
		// 连接建立时对超时的控制
		pool.setSocketConnectTO(conf.getSocketConnectTo());

		// 初始化一些值并与MemcachedServer段建立连接
		pool.initialize();

		mcc.setCompressEnable(conf.getCompressEnable());
		mcc.setCompressThreshold(conf.getCompressThreshold());

		// 确保可以在其他服务器上通信
		pool.setHashingAlg(SockIOPool.NEW_COMPAT_HASH);

		// java默认的类型没有实现序列化,可以通过这个设置开启
		mcc.setPrimitiveAsString(true);

		// 是否过滤key的编码
		mcc.setSanitizeKeys(false);
	}

	public static MemcachedFactory getInstance() {
		return instance;
	}

	public MemCachedClient getMcc() {
		return mcc;
	}
}
